<?php

namespace Snitso\IO\Reactor\Swoole\Single;


class Worker
{
    protected $socket;
    public $onConnect = null;
    public $onReceive = null;
    public $onClose = null;

    public function __construct(string $address)
    {
        $this->socket = stream_socket_server($address);
    }

    public function start()
    {
        $this->accept();
    }

    private function accept()
    {
        \Swoole\Event::add($this->socket, function ($socket) {
            $client = stream_socket_accept($socket);

            ($this->onConnect)($this, $client);

            \Swoole\Event::add($client, function ($client) {
                $data = fread($client, 65535);

                if (! trim($data) || feof($client)) {
                    //socket处理完成后，从epoll事件中移除socket
                    swoole_event_del($client);

                    fclose($client);

                    return;
                }

                ($this->onReceive)($this, $client, $data);
            });
        });
    }

    public function send($client, $data)
    {
        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/html;charset=UTF-8\r\n";
        $response .= "Connection: keep-alive\r\n";
        $response .= "Content-length: " . strlen($data) . "\r\n\r\n";
        $response .= $data;
        fwrite($client, $response);
    }
}